package com.cskaoyan.util;

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.exception.ValidationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * @author stone
 * @date 2022/07/18 10:14
 */
public class ValidationUtils {
    public static BaseRespVo validResult(BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {//是否有校验错误
            FieldError fieldError = bindingResult.getFieldError();
            Object rejectedValue = fieldError.getRejectedValue();
            String field = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();
            String msg = "请求参数" + field + "因为值" + rejectedValue + "没有通过校验：" + defaultMessage;
            return BaseRespVo.invalidParameter(msg);
        }
        return null;
    }

    public static void validResult2(BindingResult bindingResult) throws ValidationException {
        if (bindingResult.hasFieldErrors()) {//是否有校验错误
            FieldError fieldError = bindingResult.getFieldError();
            Object rejectedValue = fieldError.getRejectedValue();
            String field = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();
            String msg = "请求参数" + field + "因为值" + rejectedValue + "没有通过校验：" + defaultMessage;
            // 异常处理 → 抛出一个异常呢 → @ExceptionHandler对应的方法响应Json
            throw new ValidationException(msg);
        }
    }
    // milestone
}
